package org.zoomdev.zoom.dao.rename;

import org.zoomdev.zoom.dao.RenameStrategy;
import org.zoomdev.zoom.dao.RenameStrategyFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * 检测前缀
 * 规则：
 *
 * <pre>
 * 某表的所有字段中，具有以下划线结尾的相同起始字符串，称为"特征"字段
 * 当"特征"字段起始于第一个，且相同"特征"字段大于2个的情况下成立。
 * 例如:
 *
 * a_id,
 * a_name
 *
 * a_ 即为"前缀"
 * </pre>
 */
public class DetectPrefixStrategyFactory implements RenameStrategyFactory {


    @Override
    public RenameStrategy getStrategy(String[] columnNames) {
        int index = 0;
        String key = null;
        int count = 0;
        for (String name : columnNames) {
            String[] arr = name.split("_");
            if (arr.length < 1) {
                if (index == 0) {
                    return CamelRenameStrategy.DEFAULT;
                }
                continue;
            }

            String prefixThisColumn = arr[0];
            if (index == 0) {
                key = prefixThisColumn;
            } else {
                if (key.equals(prefixThisColumn)) {
                    ++count;
                    if (count > 1) {
                        String prefix = key + "_";
                        if (!check(prefix, columnNames)) {
                            break;
                        }
                        return new PrefixRenameStrategy(key + "_");
                    }
                }
            }
            ++index;
        }


        return CamelRenameStrategy.DEFAULT;
    }

    private boolean check(String prefix, String[] columnNames) {

        Set<String> set = new HashSet<>();
        for (String column : columnNames) {
            if (column.startsWith(prefix)) {
                column = column.substring(prefix.length());
            }
            set.add(column);
        }

        return set.size() == columnNames.length;
    }


}
